#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <sys/select.h>
#include <net/if.h>

int main(int argc, const char *argv[])
{
    // 创建套接字
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd == -1)
    {
        printf("创建套接字失败\n");
        exit(1);
    }
    struct sockaddr_in serv;
    memset(&serv, 0, sizeof(serv));
    serv.sin_addr.s_addr = htonl(INADDR_ANY);
    serv.sin_family = AF_INET;
    serv.sin_port = htons(8888);
    socklen_t len = sizeof(serv);
    bind(fd, (struct sockaddr *)&serv, len);
    struct sockaddr_in client;
    socklen_t client_len = sizeof(client);
    client.sin_family = AF_INET;
    client.sin_port = htons(6767);
    // 使用广播地址给客户端发数据
    inet_pton(AF_INET, "239.0.0.10", &client.sin_addr.s_addr);
    // 服务器开放组播权限
    struct ip_mreqn flag;
    inet_pton(AF_INET, "239.0.0.10", &flag.imr_multiaddr.s_addr);
    inet_pton(AF_INET, "0.0.0.0", &flag.imr_address.s_addr);
    flag.imr_ifindex = if_nametoindex("wlp3s0");
    setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &flag, sizeof(flag));

    while (1)
    {
        char buf[] = "hello world";
        printf("recv buf: %s\n", buf);
        sendto(fd, buf, strlen(buf) + 1, 0, (struct sockaddr *)&client, len);
        sleep(1);
    }
    close(fd);
    return 0;
}
